<template>
  <div class="alphabet">
    <ul class="list">
      <li class="item" 
      v-for="item of letter"
      :key="item"
      :ref="item"
      @click="clickHandel"
      @touchstart="handleTouchsatrt"
      @touchmove="handleTouchmove"
      @touchend="handleTouchend"
      >
      {{item}}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "cityAlphabet",
  props: {
    cities: Object
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    };
  },
  computed: {
    letter() {
      let letter = [];
      for (let item in this.cities) {
        letter.push(item);
      }
      // letter=["A","B","C",]把对象遍历成数组
      return letter;
    }
  },
  updated() {
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    clickHandel(e) {
      this.$emit("change", e.target.innerText);
    },
    handleTouchsatrt() {
      this.touchStatus = true;
    },
    handleTouchmove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          // const startY = this.$refs["A"][0].offsetTop;  //放在handleTouchmove函数里面 每次多会指向这句 不需要 所以放到updata()里面
          const touchY = e.touches[0].clientY - 79; //e.touches[0]获取事件对象  79px上面头部的高度
          const index = Math.floor((touchY - this.startY) / 20); //20 字母的高度 差值 除以字母的高度 得到索引index  letter[index]：是索引对应的字母
          if (index >= 0 && index < this.letter.length) {
            this.$emit("change", this.letter[index]);
          }
        }, 16); // 函数节流 16ms
      }
    },
    handleTouchend() {
      this.touchStatus = false;
    }
  }
};
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.alphabet {
  position: absolute;
  right: 0;
  top: 1.58rem;
  bottom: 0;
  width: 0.4rem;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .list {
    .item {
      text-align: center;
      line-height: 0.4rem;
      color: $bgColor;
    }
  }
}
</style>
